package com.example.controller;

import com.example.pojo.PageBean;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据姓名查询
     * @param name
     * @return
     */
    @GetMapping("/search")
    public Result searchByName(@RequestParam String name){
        User user = userService.findUser(name);
        return Result.success(user);
    }

    /**
     * 添加学生
     * @param user
     * @return
     */
    @PostMapping
    public Result addUser(@RequestBody User user){
        //查询是否存在这个学生
        User user1 = userService.findUser(user.getName());
        if(user1 != null){
            return Result.error("该学生已存在");
        }
        userService.addUser(user);
        return Result.success("添加学生成功");
    }

    /**
     * 修改学生
     * @param user
     * @return
     */
    @PutMapping
    public Result updateUser(@RequestBody User user){
        userService.updateUser(user);
        return Result.success("修改成功");
    }

    /**
     * 获取学生数据
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public Result getUserInfo(@RequestParam Integer id){
        User user = userService.getUserInfo(id);
        return Result.success(user);
    }

    /**
     * 删除学生
     * @param id
     * @return
     */
    @DeleteMapping
    public Result deleteUser(@RequestParam Integer id){
        userService.deleteUser(id);
        return Result.success("删除成功");
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param name
     * @param dormitoryId
     * @return
     */
    @GetMapping
    public Result PageList(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String dormitoryId,
                            @RequestParam (required = false) String categoryName){
        PageBean pageBean = userService.PageList(pageNum,pageSize,name,dormitoryId,categoryName);
        log.info(String.valueOf(pageBean));
        return Result.success(pageBean);
    }

}
